<template>
  <el-dialog
    v-model="visible"
    title="用户活动记录"
    width="900px"
    :before-close="handleClose"
  >
    <div v-loading="loading" class="activities-management">
      <!-- 活动统计 -->
      <el-row :gutter="20" class="stats-section">
        <el-col :span="6">
          <div class="stat-card total">
            <div class="stat-number">{{ activities.length }}</div>
            <div class="stat-label">总活动数</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card created">
            <div class="stat-number">{{ createdActivities }}</div>
            <div class="stat-label">创建的活动</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card participated">
            <div class="stat-number">{{ participatedActivities }}</div>
            <div class="stat-label">参与的活动</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card upcoming">
            <div class="stat-number">{{ upcomingActivities }}</div>
            <div class="stat-label">即将开始</div>
          </div>
        </el-col>
      </el-row>

      <!-- 搜索和筛选 -->
      <el-card shadow="never" class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="活动状态">
            <el-select v-model="searchForm.status" placeholder="选择状态" clearable style="width: 150px">
              <el-option label="进行中" value="ongoing" />
              <el-option label="已结束" value="finished" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="参与角色">
            <el-select v-model="searchForm.role" placeholder="选择角色" clearable style="width: 150px">
              <el-option label="创建者" value="creator" />
              <el-option label="参与者" value="participant" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 活动列表 -->
      <el-card shadow="never" class="activities-section">
        <template #header>
          <div class="section-header">
            <h4>活动列表 ({{ filteredActivities.length }} 个)</h4>
            <el-button type="success" size="small" @click="handleRefresh">
              <el-icon><refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </template>

        <div v-if="filteredActivities.length > 0" class="activities-list">
          <div
            v-for="activity in filteredActivities"
            :key="activity.id"
            class="activity-item"
            :class="getActivityClass(activity)"
          >
            <div class="activity-header">
              <div class="activity-title">
                <h5>{{ activity.title }}</h5>
                <el-tag :type="getStatusType(activity.status)" size="small">
                  {{ getStatusText(activity.status) }}
                </el-tag>
              </div>
              <div class="activity-role">
                <el-tag v-if="activity.creator_id === user.id" type="success" size="small">
                  创建者
                </el-tag>
                <el-tag v-else type="info" size="small">
                  参与者
                </el-tag>
              </div>
            </div>

            <div class="activity-details">
              <div class="detail-row">
                <span class="label">场馆:</span>
                <span class="value">{{ activity.venue_name }}</span>
              </div>
              <div class="detail-row">
                <span class="label">时间:</span>
                <span class="value">{{ formatDateTime(activity.start_time) }} - {{ formatDateTime(activity.end_time) }}</span>
              </div>
              <div class="detail-row">
                <span class="label">人数:</span>
                <span class="value">{{ activity.current_participants }}/{{ activity.max_participants }}</span>
              </div>
              <div v-if="activity.description" class="detail-row">
                <span class="label">描述:</span>
                <span class="value">{{ activity.description }}</span>
              </div>
            </div>

            <div class="activity-participants">
              <div class="participants-header">
                <span>参与者 ({{ activity.participants?.length || 0 }})</span>
                <el-button type="text" size="small" @click="toggleParticipants(activity.id)">
                  {{ expandedActivities.includes(activity.id) ? '收起' : '展开' }}
                </el-button>
              </div>
              
              <div v-if="expandedActivities.includes(activity.id)" class="participants-list">
                <div
                  v-for="participant in activity.participants"
                  :key="participant.id"
                  class="participant-item"
                >
                  <el-avatar :src="getFullImageUrl(participant.avatar_url)" :size="24">
                    <img src="https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png" />
                  </el-avatar>
                  <span class="participant-name">{{ participant.nickname }}</span>
                  <span class="join-time">{{ formatDate(participant.joined_at) }}</span>
                </div>
              </div>
            </div>

            <div class="activity-actions">
              <el-button type="primary" size="small" @click="handleViewActivity(activity)">
                查看详情
              </el-button>
              <el-button v-if="activity.creator_id === user.id" type="warning" size="small" @click="handleManageActivity(activity)">
                管理活动
              </el-button>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无活动记录" :image-size="80" />
      </el-card>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { activityApi } from '@/api/activity'

export default {
  name: 'UserActivitiesDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    user: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const visible = ref(props.modelValue)
    const loading = ref(false)
    const activities = ref([])
    const expandedActivities = ref([])
    const imageBaseUrl = ref(process.env.VUE_APP_IMAGE_BASE_URL || 'https://hm.yunxitech.cn')

    // 搜索表单
    const searchForm = reactive({
      status: '',
      role: ''
    })

    // 监听对话框显示状态
    watch(() => props.modelValue, (val) => {
      visible.value = val
      if (val && props.user?.id) {
        fetchUserActivities()
      }
    })

    watch(visible, (val) => {
      emit('update:modelValue', val)
    })

    // 计算属性
    const createdActivities = computed(() => {
      return activities.value.filter(activity => activity.creator_id === props.user?.id).length
    })

    const participatedActivities = computed(() => {
      return activities.value.filter(activity => activity.creator_id !== props.user?.id).length
    })

    const upcomingActivities = computed(() => {
      const now = new Date()
      return activities.value.filter(activity => new Date(activity.start_time) > now).length
    })

    const filteredActivities = computed(() => {
      let filtered = activities.value

      if (searchForm.status) {
        filtered = filtered.filter(activity => activity.status === searchForm.status)
      }

      if (searchForm.role) {
        if (searchForm.role === 'creator') {
          filtered = filtered.filter(activity => activity.creator_id === props.user?.id)
        } else if (searchForm.role === 'participant') {
          filtered = filtered.filter(activity => activity.creator_id !== props.user?.id)
        }
      }

      return filtered
    })

    // 获取用户活动
    const fetchUserActivities = async () => {
      loading.value = true
      try {
        const response = await activityApi.getUserActivities(props.user.id)
        activities.value = response.data.activities || []
      } catch (error) {
        ElMessage.error('获取用户活动失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    // 格式化日期时间
    const formatDateTime = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN')
    }

    // 获取活动状态样式
    const getActivityClass = (activity) => {
      const now = new Date()
      const startTime = new Date(activity.start_time)
      const endTime = new Date(activity.end_time)

      if (activity.status === 'cancelled') return 'cancelled'
      if (endTime < now) return 'finished'
      if (startTime <= now && endTime >= now) return 'ongoing'
      return 'upcoming'
    }

    const getStatusType = (status) => {
      const statusMap = {
        ongoing: 'success',
        finished: 'info',
        cancelled: 'danger',
        upcoming: 'warning'
      }
      return statusMap[status] || 'info'
    }

    const getStatusText = (status) => {
      const statusMap = {
        ongoing: '进行中',
        finished: '已结束',
        cancelled: '已取消',
        upcoming: '未开始'
      }
      return statusMap[status] || '未知'
    }

    // 切换参与者列表
    const toggleParticipants = (activityId) => {
      const index = expandedActivities.value.indexOf(activityId)
      if (index > -1) {
        expandedActivities.value.splice(index, 1)
      } else {
        expandedActivities.value.push(activityId)
      }
    }

    // 搜索
    const handleSearch = () => {
      // 筛选逻辑已在计算属性中处理
    }

    // 重置
    const handleReset = () => {
      Object.assign(searchForm, {
        status: '',
        role: ''
      })
    }

    // 刷新
    const handleRefresh = () => {
      fetchUserActivities()
    }

    // 查看活动详情
    const handleViewActivity = (activity) => {
      ElMessage.info('跳转到活动详情页面 (开发中)')
    }

    // 管理活动
    const handleManageActivity = (activity) => {
      ElMessage.info('跳转到活动管理页面 (开发中)')
    }

    // 关闭对话框
    const handleClose = () => {
      visible.value = false
      expandedActivities.value = []
    }

    function getFullImageUrl(url) {
      if (!url) return '';
      if (/^https?:\/\//.test(url)) return url;
      if (url.startsWith('/uploads/avatar/')) return imageBaseUrl.value + url;
      return `${imageBaseUrl.value}/uploads/avatar/${url.replace(/^uploads[\/\\]avatar[\/\\]/, '')}`;
    }

    return {
      visible,
      loading,
      activities,
      expandedActivities,
      searchForm,
      createdActivities,
      participatedActivities,
      upcomingActivities,
      filteredActivities,
      formatDateTime,
      formatDate,
      getActivityClass,
      getStatusType,
      getStatusText,
      toggleParticipants,
      handleSearch,
      handleReset,
      handleRefresh,
      handleViewActivity,
      handleManageActivity,
      handleClose,
      getFullImageUrl
    }
  }
}
</script>

<style scoped>
.activities-management {
  max-height: 600px;
  overflow-y: auto;
}

.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  border-radius: 8px;
  color: white;
}

.stat-card.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-card.created {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-card.participated {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-card.upcoming {
  background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
}

.stat-number {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.search-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-header h4 {
  margin: 0;
  color: #303133;
}

.activities-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.activity-item {
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fafafa;
  transition: all 0.3s ease;
}

.activity-item:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.activity-item.ongoing {
  border-color: #67c23a;
  background-color: #f0f9ff;
}

.activity-item.finished {
  border-color: #909399;
  background-color: #f5f5f5;
}

.activity-item.cancelled {
  border-color: #f56c6c;
  background-color: #fef0f0;
}

.activity-item.upcoming {
  border-color: #e6a23c;
  background-color: #fdf6ec;
}

.activity-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.activity-title {
  display: flex;
  align-items: center;
  gap: 10px;
}

.activity-title h5 {
  margin: 0;
  color: #303133;
  font-size: 16px;
}

.activity-details {
  margin-bottom: 15px;
}

.detail-row {
  display: flex;
  margin-bottom: 5px;
}

.label {
  width: 60px;
  color: #606266;
  font-size: 14px;
}

.value {
  color: #303133;
  font-size: 14px;
  flex: 1;
}

.activity-participants {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.participants-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-weight: 500;
  color: #303133;
}

.participants-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.participant-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 5px;
}

.participant-name {
  font-size: 14px;
  color: #303133;
}

.join-time {
  font-size: 12px;
  color: #909399;
  margin-left: auto;
}

.activity-actions {
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

:deep(.el-card__header) {
  padding: 15px 20px;
}

:deep(.el-card__body) {
  padding: 20px;
}
</style> 